package com.app.service;

import com.app.model.cache.RedisKeys;
import com.app.model.main.CommentsOfArticle;
import com.app.model.main.CommentsOfComments;
import com.app.model.main.RewardArticle;
import com.app.model.main.UserInfo;
import com.app.model.response.Commentsv1ResponseBody;
import com.app.model.response.Commentsv2ResponseBody;
import com.app.model.response.RetCode;
import com.app.model.response.RetStatus;
import com.app.model.util.CommonFlag;
import com.app.repository.interfaces.*;
import com.app.service.push.PushService;
import com.app.support.utils.RedisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Lichaojie on 2017/4/7. It's a beautiful day.
 */
@Service
public class CommentsService {

    @Autowired
    private ResponseService responseService;
    @Autowired
    private CommentsOfArticleMapper commentsOfArticleMapper;
    @Autowired
    private CommentsOfCommentsMapper commentsOfCommentsMapper;
    @Autowired
    private PushService pushService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private ApprovalMapper approvalMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RewardArticleMapper rewardArticleMapper;

    public RetStatus submitCommentsv1( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int articleId = (int)paraMap.get("id");
        int userId = (int)paraMap.get("userId");
        String time = (String)paraMap.get("time");
        String content = (String)paraMap.get("content");

        CommentsOfArticle commentsOfArticle = new CommentsOfArticle();
        commentsOfArticle.setUserId((long)userId)
                .setArticleId((long)articleId)
                .setTime(time)
                .setContent(content);

        if(commentsOfArticleMapper.insertSelective(commentsOfArticle) == 1){
            pushService.pushNotification(commentsOfArticle);

            String commentsKey = RedisKeys.COMMENTS_NUMBER_OF_ARTICLE + articleId;
            long approvalNum = 0;
            if(redisUtil.exists(commentsKey)){
                approvalNum = ((Integer)redisUtil.get(commentsKey)).longValue();
            }
            redisUtil.set(commentsKey, approvalNum + 1);

            return responseService.doResponse(100);
        }else {
            return responseService.doResponse(200);
        }
    }

    public RetStatus getCommentsv1Update( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int articleId = (int)paraMap.get("id");
        int lastId = (int)paraMap.get("lastId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<CommentsOfArticle> commentsOfArticleList;
        if(page == 0){//第一次进入此页面
            commentsOfArticleList = commentsOfArticleMapper.getListOrderedByIdDESC(articleId,commentsOfArticleMapper.getMaxId() + 1,page,number);
        }else {
            commentsOfArticleList = commentsOfArticleMapper.getListOrderedByIdASC(articleId, lastId, page, number);
        }

        if(commentsOfArticleList != null && commentsOfArticleList.size() > 0){
            List<Commentsv1ResponseBody> resultList = new ArrayList<>();
            for (CommentsOfArticle commentsOfArticle : commentsOfArticleList){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(commentsOfArticle.getUserId());
                Commentsv1ResponseBody commentsv1ResponseBody = new Commentsv1ResponseBody();
                commentsv1ResponseBody.setUserId(userInfo.getId())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setNickName(userInfo.getNickName())
                        .setCommentsv1Id(commentsOfArticle.getId())
                        .setContent(commentsOfArticle.getContent())
                        .setTime(commentsOfArticle.getTime())
                        .setApprovalNum(approvalMapper.getApprovalNumber(commentsOfArticle.getId(), CommonFlag.COMMENTS))
                        .setCommentNum(commentsOfCommentsMapper.getCommentsv2Number(commentsOfArticle.getId()));
                resultList.add(commentsv1ResponseBody);
            }


            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(216);
        }
    }


    public RetStatus getCommentsv1Reward(String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int moreOrUpdate = (int)paraMap.get("type");

        if(moreOrUpdate == 0) { //TODO 需要确定加载更多或更新的参数 0-更新 1-加载更多
            return getCommentsv1RewardUpdate(parameter);
        }else{
            return getCommentsv1LoadMore(parameter);
        }
    }


    public RetStatus getCommentsv1RewardUpdate( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int articleId = (int)paraMap.get("id");
        int lastId = (int)paraMap.get("lastId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<CommentsOfArticle> commentsOfArticleList;
        if(page == 0){//第一次进入此页面
            commentsOfArticleList = commentsOfArticleMapper.getListOrderedByIdDESC(articleId,commentsOfArticleMapper.getMaxId() + 1,page,number);
            RewardArticle rewardArticle = rewardArticleMapper.getByArticleId((long)articleId);
            if(rewardArticle != null && rewardArticle.getStatus() == (byte)1) {
                long commentId = rewardArticle.getCommentId();
                CommentsOfArticle commentsOfArticle = commentsOfArticleMapper.selectByPrimaryKey(commentId);
                if(commentsOfArticleList.contains(commentsOfArticle))
                    commentsOfArticleList.remove(commentsOfArticle);
                commentsOfArticleList.set(0, commentsOfArticle);
            }
        }else {
            commentsOfArticleList = commentsOfArticleMapper.getListOrderedByIdASC(articleId, lastId, page, number);
        }

        if(commentsOfArticleList != null && commentsOfArticleList.size() > 0){
            List<Commentsv1ResponseBody> resultList = new ArrayList<>();
            for (CommentsOfArticle commentsOfArticle : commentsOfArticleList){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(commentsOfArticle.getUserId());
                Commentsv1ResponseBody commentsv1ResponseBody = new Commentsv1ResponseBody();
                commentsv1ResponseBody.setUserId(userInfo.getId())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setNickName(userInfo.getNickName())
                        .setCommentsv1Id(commentsOfArticle.getId())
                        .setContent(commentsOfArticle.getContent())
                        .setTime(commentsOfArticle.getTime())
                        .setApprovalNum(approvalMapper.getApprovalNumber(commentsOfArticle.getId(), CommonFlag.COMMENTS))
                        .setCommentNum(commentsOfCommentsMapper.getCommentsv2Number(commentsOfArticle.getId()));
                resultList.add(commentsv1ResponseBody);
            }


            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(216);
        }
    }

    public RetStatus getCommentsv1LoadMore( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int articleId = (int)paraMap.get("id");
        int lastId = (int)paraMap.get("lastId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<CommentsOfArticle> commentsOfArticleList = null;
        commentsOfArticleList = commentsOfArticleMapper.getListOrderedByIdDESC(articleId, lastId, page, number);
        if(commentsOfArticleList != null && commentsOfArticleList.size() > 0){
            List<Commentsv1ResponseBody> resultList = new ArrayList<>();
            for (CommentsOfArticle commentsOfArticle : commentsOfArticleList){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(commentsOfArticle.getUserId());
                Commentsv1ResponseBody commentsv1ResponseBody = new Commentsv1ResponseBody();
                commentsv1ResponseBody.setUserId(userInfo.getId())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setNickName(userInfo.getNickName())
                        .setCommentsv1Id(commentsOfArticle.getId())
                        .setContent(commentsOfArticle.getContent())
                        .setTime(commentsOfArticle.getTime())
                        .setApprovalNum(approvalMapper.getApprovalNumber(commentsOfArticle.getId(), CommonFlag.COMMENTS))
                        .setCommentNum(commentsOfCommentsMapper.getCommentsv2Number(commentsOfArticle.getId()));
                resultList.add(commentsv1ResponseBody);
            }


            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(216);
        }
    }


    public RetStatus submitCommentsv2( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int commentId = (int)paraMap.get("commentId");
        int userId = (int)paraMap.get("userId");
        String time = (String)paraMap.get("time");
        String content = (String)paraMap.get("content");

        CommentsOfComments commentsOfComments = new CommentsOfComments();
        commentsOfComments.setCommentsId((long)commentId)
                .setUserId((long)userId)
                .setTime(time)
                .setContent(content);

        if(commentsOfCommentsMapper.insertSelective(commentsOfComments) == 1){
            pushService.pushNotification(commentsOfComments);
            return responseService.doResponse(100);
        }else{
            return responseService.doResponse(200);
        }
    }

    public RetStatus getCommentsv2Update( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int commentsv1Id = (int)paraMap.get("id");
        int lastId = (int)paraMap.get("lastId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<CommentsOfComments> commentsOfCommentsList;
        if(page == 0){//第一次进入此页面
            commentsOfCommentsList = commentsOfCommentsMapper.getListOrderedByIdDESC(commentsv1Id,commentsOfCommentsMapper.getMaxId() + 1,page,number);
        }else {
            commentsOfCommentsList = commentsOfCommentsMapper.getListOrderedByIdASC(commentsv1Id,lastId,page,number);
        }

        if(commentsOfCommentsList != null && commentsOfCommentsList.size() > 0){
            List<Commentsv2ResponseBody> resultList = new ArrayList<>();
            for (CommentsOfComments commentsOfComments : commentsOfCommentsList){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(commentsOfComments.getUserId());
                Commentsv2ResponseBody commentsv2ResponseBody = new Commentsv2ResponseBody();
                commentsv2ResponseBody.setUserId(userInfo.getId())
                        .setNickName(userInfo.getNickName())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setCommentsv2Id(commentsOfComments.getId())
                        .setContent(commentsOfComments.getContent())
                        .setTime(commentsOfComments.getTime());
                resultList.add(commentsv2ResponseBody);
            }


            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(216);
        }
    }

    public RetStatus getCommentsv2LoadMore( String parameter){
        ObjectMapper objectMapper = new ObjectMapper();
        Map paraMap = null;
        try{
            paraMap = objectMapper.readValue(parameter,Map.class);
        }catch (IOException e){
            e.printStackTrace();
            return responseService.doResponse(204);
        }

        int commentsv1Id = (int)paraMap.get("id");
        int lastId = (int)paraMap.get("lastId");
        int page = (int)paraMap.get("page");
        int number = (int)paraMap.get("number");

        List<CommentsOfComments> commentsOfCommentsList = null;
        commentsOfCommentsList = commentsOfCommentsMapper.getListOrderedByIdDESC(commentsv1Id,lastId,page,number);
        if(commentsOfCommentsList != null && commentsOfCommentsList.size() > 0){
            List<Commentsv2ResponseBody> resultList = new ArrayList<>();
            for (CommentsOfComments commentsOfComments : commentsOfCommentsList){
                UserInfo userInfo = userInfoMapper.selectByPrimaryKey(commentsOfComments.getUserId());
                Commentsv2ResponseBody commentsv2ResponseBody = new Commentsv2ResponseBody();
                commentsv2ResponseBody.setUserId(userInfo.getId())
                        .setNickName(userInfo.getNickName())
                        .setAvator(imageMapper.selectByPrimaryKey(userInfo.getAvator()).getOrigin())
                        .setCommentsv2Id(commentsOfComments.getId())
                        .setContent(commentsOfComments.getContent())
                        .setTime(commentsOfComments.getTime());
                resultList.add(commentsv2ResponseBody);
            }

            RetStatus retStatus = new RetStatus();
            retStatus.setCode(100)
                    .setMessage(RetCode.getMessage(100))
                    .setBody(resultList);
            return retStatus;
        }else {
            return responseService.doResponse(216);
        }
    }



    /**
     * 获取userId对应的用户在days天内评论他人帖子的次数
     * @param days
     * @param userId
     * @return
     */
    public int getCommentsTimesByDay(int days,long userId){
        long time2 = System.currentTimeMillis();
        long time1 = time2 - 24 * 60 * 60 * 1000 * days;

        List<CommentsOfArticle> commentsOfArticleList =
                commentsOfArticleMapper.getListByUserIdBetween(userId,Long.toString(time1),Long.toString(time2));

        if(commentsOfArticleList == null){
            return 0;
        }else {
            return commentsOfArticleList.size();
        }
    }


}
